package com.example.WebTask1.Controller;

import com.example.WebTask1.Enity.User;
import com.example.WebTask1.Service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "ServletLogin", urlPatterns = "/login")
public class ServletLogin extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+password);
        UserService userService = new UserService();
        User user = new User(username,password);
        boolean userinfo = userService.userinfo(username, password);
        if (userinfo){

            Cookie cookie = new Cookie("user",user.getUser());
            response.addCookie(cookie);
            cookie.setMaxAge(60*60*24*7);//cookies有效期一个星期
            HttpSession session = request.getSession();
            session.setAttribute("user",username);
            session.getAttribute("user");
            response.sendRedirect("choice.jsp");
            System.out.println("登入成功");
        }else {
            request.getRequestDispatcher("index.jsp").forward(request,response);
            System.out.println("登入失败");
        }

    }
}
